import os
import sys
import time

import numpy as np

sys.path.append(os.path.abspath("..\\multiagent-particle\\multiagent-particle-envs"))
import gymnasium as gym
import math

import AirCombat_demo as env
PlaneRed = env.get_plane_red()

def GetCReward():

    AREA_LON_MIN = env.Lon_min()
    AREA_LON_MAX = env.Lon_max()
    AREA_LAT_MIN = env.Lat_min()
    AREA_LAT_MAX = env.Lat_max()

    # 获取环境数据
    current_lon = env.Get_longitude0()
    current_lat = env.Get_latitude0()
    repeat_capture = env.Get_repeatCapture0()
    distance = PlaneRed.RedOutData.output_info[0].theta_dis
    azimuth = PlaneRed.RedOutData.output_info[0].diff_deg
    new_capture = env.Get_newCapture0()
    radar_capture = PlaneRed.RedOutData.output_info[0]._raderCapture
    out_area = env.out_done()
    position_done = env.position_done(40)
    alt = env.Get_altitude0()
    num_grid=env.getCumulativeScannedGridCount()  #栅格的捕获数量
    rate_grid=env.rate()
    new_grid = env.Capture_grid()
    roll = env.Get_roll0()
    # ================= 核心奖励项 =================
    # ================= 核心奖励函数设计 =================
    total_grids = 2500  # 总栅格数
    grid_reward=0
    # grid_reward = (new_grid * 0.2)
    # grid_reward *= (1 + num_grid / total_grids)
    # 2. 覆盖率进度奖励 (指数增长，鼓励后期覆盖)
    # 公式：progress_reward = k * (current_coverage)^n


    roll_penalty = 0
    if  abs(roll>10):
        roll_penalty = -0.01

    # grid_reward += new_grid *0.1 +num_grid/total_grids
    grid_reward += new_grid *0.5


    if env.num_done():
        grid_reward += 10

    # 3. 区域保持奖励（连续惩罚）
    lon_penalty = max(AREA_LON_MIN - current_lon, current_lon - AREA_LON_MAX, 0)
    lat_penalty = max(AREA_LAT_MIN - current_lat, current_lat - AREA_LAT_MAX, 0)
    boundary_distance = np.sqrt(lon_penalty ** 2 + lat_penalty ** 2)
    area_penalty = -0.5 * (boundary_distance ** 1.5)  # 指数型惩罚

    # 4. 越界-20
    if out_area == True:
        out_reward = -10
        # print("越界")
    else:
        out_reward = 0
    if position_done == True:
        position_done_reward = 20
        # print("闭合")
    else:
        position_done_reward = 0
    if alt <5000:
        alt_reward = -10
    else:
        alt_reward = 0



        # ================= 合成总奖励 =================
    total_reward = (
                grid_reward
                # roll_penalty
                # alt_reward


        # dis_reward +
                # survive_reward +
                # area_penalty +
                # out_reward +
                # position_done_reward
        )
    return total_reward